import React from 'react';
import { Table, Icon, Modal, Checkbox, Slider, Button, message } from 'antd'
import { messages, deepCopy } from 'share/common'
import ListSort from 'components/list-sort'
import ReactDOM from 'react-dom'

class ColumnsConfig extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      tableWidth: props.tableWidth,
      hasFixed: false,
      scrollX: 0,
      refreshListSortFlag: true,
    }
  }

  componentDidMount(){
    this.readConfig();
  }

  componentWillReceiveProps(nextProps) {
    const { tableWidth } = this.state;
    if(nextProps.tableWidth && nextProps.tableWidth !== tableWidth)
      this.setState({ tableWidth: nextProps.tableWidth }, () => this.readConfig());
  }

  readConfig = () => {
    const { tableWidth } = this.state;
    const { allColumns, tableOption, localKey } = this.props;
    let columns = deepCopy(allColumns);
    let leftFixed = [], rightFixed = [], noFixed = [];
    let hasFixed = false;
    let scrollX = 0;
    columns.map(c => {
      //百分比转换成px
      if(typeof c.width === 'string'){
        if(c.width.indexOf('px') > -1){
          c.width = Number(c.width.substr(0, c.width.length - 2));
        } else {
          c.width = Math.floor(Number(c.width.substr(0,c.width.length - 1)) * tableWidth * 0.01);
        }
      }
      c.selected = tableOption.columns.filter(tc => tc.dataIndex === c.dataIndex).length > 0;
      c.fixed === 'left' && leftFixed.push(c) && ( hasFixed = true );
      c.fixed === 'right' && rightFixed.push(c) && ( hasFixed = true );
      !c.fixed && noFixed.push(c);
    });
    if (hasFixed) {
      columns.map(c => {
        if(!c.width) {
          // https://pmo.mcd.com.cn/jira/browse/TES-1564
          // 默认“序号列”固定在左侧，此时表格列不能有auto，这里默认自动宽度的列为120
          c.width = 120;
        }
        scrollX += c.width;
      })
    }
    //左浮动、不浮动、又浮动顺序排序
    columns = [].concat(leftFixed, noFixed, rightFixed);
    let localConfig = localStorage.getItem('hly.tableConfig');
    if(localConfig && localConfig !== 'null'){
      localConfig = JSON.parse(localConfig);
      let localItem = localConfig[localKey];
      if(localItem){
        hasFixed = localItem.hasFixed;
        scrollX = localItem.scrollX;
        let targetColumns = [];
        localItem.columns.map(c => {
          columns.map(item => {
            if(item.dataIndex === c.dataIndex){
              item.width = c.width;
              item.selected = c.selected;
              item.fixed = c.fixed;
              targetColumns.push(item)
            }
          });
        });
        columns = [].concat(targetColumns);
      }
    }
    if(columns.filter(c => !c.width).length === 0 && !hasFixed){
      for(let i = columns.length - 1; i > 0; i--){
        if(columns[i].selected && columns[i].width){
          delete columns[i].width;
          break;
        }
      }
    }
    this.setState({ columns, hasFixed, scrollX });
    this.props.onClose({ columns, hasFixed, scrollX });
  };

  computeConfig = () => {
    let columnsListDom = ReactDOM.findDOMNode(this.refs.columnsList);
    let getItemList = className => columnsListDom
      .getElementsByClassName(className)[0]
      .getElementsByClassName('custom-column-item');
    let leftColumnsDom = getItemList('left-columns');
    let centerColumnsDom = getItemList('no-columns');
    let rightColumnsDom = getItemList('right-columns');
    //根据dom顺序确定最后的排序顺序，用title做判断
    let getNameByDom = doms => {
      let names = [];
      doms.map(dom => {
        for(let i = 0; i < dom.length; i++){
          let name = dom[i].getElementsByClassName('column-name')[0].innerText;
          //兼容火狐
          if(!name) name = dom[i].getElementsByClassName('column-name')[0].textContent;
          names.push(name);
        }
      });
      return names;
    };
    let names = getNameByDom([leftColumnsDom, centerColumnsDom, rightColumnsDom]);
    const { columns } = this.state;
    let targetColumns = [];
    let scrollX = 0;
    names.map(name => {
      targetColumns.push(columns.find(c => c.title === name))
    });
    //计算scrollX
    targetColumns.map(c => {
      if(!c.fixed && c.selected)
        scrollX += c.width;
    });
    return {
      columns: targetColumns,
      scrollX
    }
  };

  handleClose = () => {
    let result = this.computeConfig();
    const { hasFixed } = this.state;
    const { tableWidth } = this.props;
    let width = 0;
    result.columns.map(c => { c.width && c.selected && ( width += c.width ) });
    if(width > tableWidth && !hasFixed){
      Modal.confirm({
        title: messages('components.key464')/*提示*/,
        content: messages('components.key687')/*总宽度超过了表格宽度，是否保存？*/,
        onOk: () => {
          this.saveConfig(result);
        }
      });
    } else {
      this.saveConfig(result);
    }
  };

  saveConfig = result => {
    const { hasFixed } = this.state;
    const { localKey } = this.props;
    let localConfig = localStorage.getItem('hly.tableConfig');
    localConfig = localConfig ? JSON.parse(localConfig) : {};
    if(typeof localConfig === 'string' || !localConfig)
      localConfig = {};
    localConfig[localKey] = {
      columns: result.columns.map(c => ({
        dataIndex: c.dataIndex,
        width: c.width,
        selected: c.selected,
        fixed: c.fixed
      })),
      scrollX: result.scrollX,
      hasFixed
    };
    localStorage.setItem('hly.tableConfig', JSON.stringify(localConfig));
    this.setState({
      columns: result.columns,
      scrollX: result.scrollX
    }, () => {
      this.props.onClose({
        columns: result.columns,
        scrollX: result.scrollX,
        hasFixed
      })
    })
  };

  handleChangeSelected = (e, item) => {
    e.stopPropagation();
    let { columns, hasFixed } = this.state;
    if(columns.filter(c => c.selected).length === 1 && columns.find(c => c.dataIndex === item.index).selected){
      message.error(messages('components.key688')/*每一个表格必须有一个列及以上！*/)
    }
    columns.map(c => {
      if(c.dataIndex === item.dataIndex){
        c.selected = !c.selected;
      }
    });
    if(!hasFixed && columns.filter(c => c.selected && !c.width).length === 0){
      for(let i = columns.length - 1; i > 0; i--){
        if(columns[i].selected){
          delete columns[i].width;
          break;
        }
      }
    }
    this.setState({ columns }, this.disabledSlideEvent)
  };

  componentDidUpdate(prevProps) {
    if(!prevProps.visible && this.props.visible) {
      this.disabledSlideEvent()
    }
  }

  //因为官方slider bug，所以此处禁止掉slider的事件，只有handle才能继续事件
  disabledSlideEvent = () => {
    let columnsListDom = ReactDOM.findDOMNode(this.refs.columnsList);
    let sliders = columnsListDom.getElementsByClassName('ant-slider');
    for(let i = 0; i < sliders.length; i++) {
      sliders[i].onmousedown = e => {
        if(e.target.className !== 'ant-slider-handle ant-tooltip-open')
          e.stopPropagation();
      };
    }
  };

  handleSort = (result, placement) => {
    this.setState(this.computeConfig())
  };

  handleChangeWidth = (width, item) => {
    const { columns } = this.state;
    const { tableWidth } = this.props;
    //delete后官方会默认调用最大值的onChange，所以这里判断是否最大值，如果是则是点击自动宽度出现的，放弃用户能够手动调整到最大值的功能
    if(width !== tableWidth - 172){
      columns.map(c => {
        if(c.dataIndex === item.dataIndex){
          c.width = width
        }
      });
      this.setState({ columns })
    }
  };

  handleChangeAuto = (e, item) => {
    e.stopPropagation();
    const { columns } = this.state;
    let index = 0;
    columns.map((c, i) => {
      c.dataIndex === item.dataIndex && (index = i);
    });
    if(columns[index].width){
      delete columns[index].width;
    } else {
      if(columns.filter(c => !c.width).length === 1){
        message.error(messages('components.key689')/*一个表格内至少应有一个自动宽度列！*/);
        return ;
      }
      columns[index].width = 80;
    }
    this.setState({ columns })
  };

  handleChangeFixed = (e, item, fixed) => {
    e.stopPropagation();
    const { columns } = this.state;
    let hasFixed = false;
    columns.map(c => {
      if(c.dataIndex === item.dataIndex){
        if(fixed){
          c.fixed = fixed;
          //改成浮动时，给一个默认值，浮动的宽度不能为auto
          if(!c.width){
            c.width = 120;
          }
        }
        else{
          delete c.fixed;
        }
      }
      hasFixed = hasFixed || !!c.fixed
    });
    if(hasFixed){
      //fixed模式下所有列都需要宽度
      columns.map(c => {
        if(!c.width){
          c.width = 120;
        }
      })
    } else {
      if(columns.filter(c => c.selected && !c.width).length === 0){
        for(let i = columns.length - 1; i > 0; i--){
          if(columns[i].selected){
            delete columns[i].width;
            break;
          }
        }
      }
    }
    this.setState({ refreshListSortFlag: false, columns, hasFixed }, () => {
      this.setState({ refreshListSortFlag: true }, () => {
        this.setState(this.computeConfig(), this.disabledSlideEvent)
      })
    });
  };

  handleMouseDown = e => {
    e.stopPropagation();
  };

  renderListSort = placement => {
    const { columns, hasFixed } = this.state;
    const { tableWidth } = this.props;
    let hasItem = columns.filter(item => placement ? (item.fixed === placement) : !item.fixed).length > 0;
    return hasItem ? (
      <ListSort
        onChange={result => this.handleSort(result, placement)}
        className="sort-container"
        dragClassName="drag-sort-list"
      >
        {columns.filter(item => placement ? (item.fixed === placement) : !item.fixed).map(item => {
          return (
            <div className="custom-column-item" key={item.dataIndex}>
              <div className="selected-icon" onMouseDown={this.handleMouseDown}>
                <Checkbox
                  checked={item.selected}
                  onChange={e => this.handleChangeSelected(e, item)}
                />
              </div>
              <div className="column-width">
                <div className="column-name">{item.title}</div>
                <Slider
                  max={tableWidth - 172}
                  min={1}
                  value={item.width || tableWidth}
                  onChange={width => this.handleChangeWidth(width, item)}
                  disabled={!item.width}
                  tipFormatter={value => `${value}px`}
                />
              </div>

              {!placement ? (
                <div className="column-operation">
                  <Icon
                    type="left-square-o"
                    title={messages('components.key673')/*左固定*/}
                    onMouseDown={this.handleMouseDown}
                    onClick={e => this.handleChangeFixed(e, item, 'left')}
                  />
                  <span className="ant-divider" />
                  { !hasFixed && [
                    <Icon
                      type={item.width ? 'pushpin-o' : 'pushpin'}
                      title={messages('components.key674')/*自动宽度*/}
                      onMouseDown={this.handleMouseDown}
                      onClick={e => this.handleChangeAuto(e, item)} key="auto"
                    />,
                    <span className="ant-divider" key="divide"/>
                  ] }

                  <Icon
                    type="right-square-o"
                    title={messages('components.key675')/*右固定*/}
                    onMouseDown={this.handleMouseDown}
                    onClick={e => this.handleChangeFixed(e, item, 'right')}
                  />
                </div>
              ) : (
                <div className="column-operation">
                  {placement === 'right' && [
                    <Icon
                      type="left-square-o"
                      title={messages('components.key673')/*左固定*/}
                      onMouseDown={this.handleMouseDown}
                      onClick={e => this.handleChangeFixed(e, item, 'left')}
                      key="left"
                    />,
                    <span className="ant-divider" key="divide"/>
                  ]}
                  <Icon
                    type="unlock"
                    title={messages('components.key676')/*取消固定*/}
                    onMouseDown={this.handleMouseDown}
                    onClick={e => this.handleChangeFixed(e, item)}
                  />
                  {placement === 'left' && [
                    <span className="ant-divider" key="divide"/>,
                    <Icon
                      type="right-square-o"
                      title={messages('components.key675')/*右固定*/}
                      onMouseDown={this.handleMouseDown}
                      onClick={e => this.handleChangeFixed(e, item, 'right')}
                      key="right"
                    />
                  ]}
                </div>
              )}
            </div>
          )}
        )}
      </ListSort>
    ) : <p style={{ color: '#c5c5c5', marginBottom: 0}}>{messages('components.key677')/*暂时还没有列哦*/}</p>
  };

  render() {
    const { tableOption, visible } = this.props;
    const { columns, refreshListSortFlag, scrollX, hasFixed, tableWidth } = this.state;
    return (
      <div>
        <Modal
          visible={visible}
          title={messages('components.key678')/*自定义*/}
          onCancel={this.handleClose}
          className="custom-table-modal"
          width={tableWidth + 48}
          footer={[
            <Button onClick={this.handleClose} key="cancel">{messages('components.key461')/*关闭*/}</Button>
          ]}>

          {refreshListSortFlag && (
            <div ref="columnsList">
              <div className="custom-table-title">{messages('components.key679')/*自定义效果预览*/}</div>
              <Table
                columns={columns.filter(c => c.selected)}
                scroll={hasFixed ? { x: scrollX } : {}}
                size={tableOption.size}
                bordered={tableOption.bordered}
              />
              <br/>
              <div className="tips">
                <div>tips: </div>
                <span>
                  {messages('components.key680')/*1、上下拖动可排序，点击*/}
                  <Icon type='left-square-o'/> 、<Icon type='right-square-o'/>
                  {messages('components.key681')/*可将列固定在最左/最右，点击*/}
                  <Icon type='unlock'/>
                  {messages('components.key682')/*可取消固定。*/}
                </span>
                <br/>
                <span>
                  {messages('components.key683')/*2、点击*/}
                  <Icon type='pushpin-o'/>
                  {messages('components.key684')/*可将列的宽度设置为自动（均分剩余宽度）,再次点击取消自动。*/}
                </span>
              </div>
              <br/>

              <div className='custom-table-row-area'>
                <div className="custom-table-title">{messages('components.key673')/*左固定*/}</div>
                <div className="left-columns">
                  {this.renderListSort('left')}
                </div>
                <br/>
                <div className="custom-table-title">{messages('components.key685')/*中间列*/}</div>
                <div className="no-columns">
                  {this.renderListSort()}
                </div>
                <br/>
                <div className="custom-table-title">{messages('components.key675')/*右固定*/}</div>
                <div className="right-columns">
                  {this.renderListSort('right')}
                </div>
              </div>

            </div>
          )}
        </Modal>
      </div>
    );
  }
}

ColumnsConfig.PropTypes = {
  localKey: React.PropTypes.string,
  tableOption: React.PropTypes.object,
  allColumns: React.PropTypes.array,
  visible: React.PropTypes.bool,
  tableWidth: React.PropTypes.number,
  onClose: React.PropTypes.func
};

export default ColumnsConfig;
